import {
    Controller,
    Post,
    UploadedFile,
    UploadedFiles,
    UseInterceptors,
    BadRequestException,
} from '@nestjs/common';
import {
    FileInterceptor,
    FilesInterceptor,
} from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname, join } from 'path';
import * as fs from 'fs';
import { Public } from 'src/auth/public.decorator';
import { ResponseFactory } from '../result/result.factory';

@Controller('/upload')
export class UploadController {
    private readonly uploadPath = join(__dirname, '..', 'files');

    constructor() {
        if (!fs.existsSync(this.uploadPath)) {
            fs.mkdirSync(this.uploadPath, { recursive: true });
        }
    }

    private static customFileName(_: any, file: { originalname: string }, cb: (arg0: null, arg1: string) => void) {
        const fileExtName = extname(file.originalname);
        const baseName = file.originalname.replace(fileExtName, '');
        const timestamp = Date.now();
        const random = Math.floor(Math.random() * 1e6);
        const newName = `${baseName}-${timestamp}-${random}${fileExtName}`;
        cb(null, newName);
    }

    @Public()
    @Post('/file')
    @UseInterceptors(
        FileInterceptor('file', {
            storage: diskStorage({
                destination: (_, _file, cb) => {
                    cb(null, join(__dirname, '..', 'files'));
                },
                filename: UploadController.customFileName,
            }),
            limits: { fileSize: 5 * 1024 * 1024 },
            fileFilter: (req, file, cb) => {
                const allowedMimeTypes = ['image/jpeg', 'image/png'];
                if (allowedMimeTypes.includes(file.mimetype)) {
                    cb(null, true);
                } else {
                    cb(new BadRequestException('文件类型不允许'), false);
                }
            },
        }),
    )
    uploadSingle(@UploadedFile() file: Express.Multer.File) {
        if (!file) return ResponseFactory.error('上传失败或无效的文件');

        return ResponseFactory.success({
            filename: file.filename,
            originalname: file.originalname,
            url: `/files/${file.filename}`,
            size: file.size,
        }, '上传成功');
    }

    @Public()
    @Post('/files')
    @UseInterceptors(
        FilesInterceptor('files', 10, {
            storage: diskStorage({
                destination: (req, _file, cb) => {
                    cb(null, join(__dirname, '..', 'files'));
                },
                filename: UploadController.customFileName,
            }),
            limits: { fileSize: 5 * 1024 * 1024 },
            fileFilter: (req, file, cb) => {
                const allowedMimeTypes = ['image/jpeg', 'image/png'];
                if (allowedMimeTypes.includes(file.mimetype)) {
                    cb(null, true);
                } else {
                    cb(new BadRequestException('文件类型不允许'), false);
                }
            },
        }),
    )
    uploadMultiple(@UploadedFiles() files: Express.Multer.File[]) {
        if (!files || files.length === 0) return ResponseFactory.error('上传失败或文件为空');

        const result = files.map((file) => ({
            filename: file.filename,
            originalname: file.originalname,
            url: `/files/${file.filename}`,
            size: file.size,
        }));

        return ResponseFactory.success(result, '上传成功');
    }
}
